<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="popup-container">
      <view class="popup-header">
        <text class="popup-title">{{ isEditMode ? '编辑物料' : '添加物料' }}</text>
        <text class="close-icon" @click="closePopup">×</text>
      </view>

      <view class="form-container">
        <view class="form-item">
          <text class="label">物料名称</text>
          <input
            class="input"
            placeholder="请输入物料名称(可选)"
            v-model="itemForm.name"
          />
        </view>

        <view class="form-item">
          <text class="label">更换周期(月)</text>
          <picker
            mode="selector"
            class="picker-selector"
            :range="cycleOptions"
            range-key="label"
            @change="onCycleChange"
            :value="selectedCycleIndex"
          >
            <view class="picker-input">
              {{ selectedCycleLabel || '请选择更换周期(必选)' }}
            </view>
          </picker>
        </view>

        <view class="button-group">
          <button class="cancel-btn" @click="closePopup">取&emsp;&emsp;消</button>
          <button class="confirm-btn" @click="confirmAction">{{ isEditMode ? `保&emsp;&emsp;存` : `确&emsp;&emsp;定` }}</button>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { defineExpose, ref } from 'vue'
import type { ItemType } from '@/stores/modules/item'
import { useItemStore } from '@/stores/modules/item'
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import { onShow } from '@dcloudio/uni-app'

const itemStore = useItemStore()
const popup = ref(null)
onShow(() => {
  // .....
})

// 表单数据
const itemForm = ref({
  name: '',
  replacementCycle: '',
})

// 更换周期选项
const cycleOptions = ref(Array.from({ length: 24 }, (_, i) => ({
  label: `${i + 1}个月`,
  value: i + 1,
})))

// 选中的周期索引和标签
const selectedCycleIndex = ref(0)
const selectedCycleLabel = ref('')

// 模式：false 为新增，true 为编辑
const isEditMode = ref(false)
const currentItemId = ref('')

// 显示新增弹窗
const showAddPopup = () => {
  isEditMode.value = false
  currentItemId.value = ''
  itemForm.value = {
    name: '',
    replacementCycle: '',
  }
  // 重置选中的周期
  selectedCycleIndex.value = 0
  selectedCycleLabel.value = ''
  if (popup.value) {
    popup.value.open()
  }
}

// 显示编辑弹窗
const showEditPopup = (item: ItemType) => {
  isEditMode.value = true
  currentItemId.value = item.id
  itemForm.value = {
    name: item.name,
    replacementCycle: item.replacementCycle.toString(),
  }
  // 设置选中的周期
  selectedCycleIndex.value = item.replacementCycle - 1
  selectedCycleLabel.value = `${item.replacementCycle}个月`
  if (popup.value) {
    popup.value.open()
  }
}

// 关闭弹窗
const closePopup = () => {
  if (popup.value) {
    popup.value.close()
    // 重置表单
    itemForm.value = {
      name: '',
      replacementCycle: '',
    }
    // 重置选中的周期
    selectedCycleIndex.value = 0
    selectedCycleLabel.value = ''
    isEditMode.value = false
    currentItemId.value = ''
  }
}

// 处理周期选择
const onCycleChange = (e: any) => {
  const selectedIndex = e.detail.value
  selectedCycleIndex.value = selectedIndex
  selectedCycleLabel.value = cycleOptions.value[selectedIndex].label
  itemForm.value.replacementCycle = cycleOptions.value[selectedIndex].value
}

// 确认操作（新增或编辑）
const confirmAction = () => {
  if (!itemForm.value.replacementCycle) {
    uni.showToast({
      title: '请选择更换周期',
      icon: 'none',
    })
    return
  }

  const cycle = parseInt(itemForm.value.replacementCycle)

  if (isEditMode.value) {
    // 编辑模式
    itemStore.updateItemType(currentItemId.value, {
      name: itemForm.value.name,
      replacementCycle: cycle,
    })

    uni.showToast({
      title: '修改成功',
      icon: 'success',
    })
  } else {
    // 新增模式
    // 如果没有填写名称，使用默认名称
    const name = itemForm.value.name || `物料${new Date().toISOString().split('T')[0]}`

    // 添加物料
    itemStore.addItemType({
      name,
      replacementCycle: cycle,
      lastReplacementDate: new Date().toISOString(),
      groupId: itemStore.currentGroupId,
    })

    uni.showToast({
      title: '添加成功',
      icon: 'success',
    })
  }

  // 关闭弹窗
  setTimeout(() => {
    closePopup()
  }, 1000)
}

// 暴露方法给父组件
defineExpose({
  showAddPopup,
  showEditPopup,
  closePopup,
})
</script>

<style lang="scss">
.popup-container {
  width: 90vw;
  background-color: #ffffff;
  border-radius: 10rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 20rpx;
  background-color: #27ba9b;
  color: #ffffff;
}

.popup-title {
  font-size: 50rpx;
  font-weight: bold;
  text-align: center;
  width: 100%;

}

.close-icon {
  font-size: 50rpx;
  font-weight: normal;
  cursor: pointer;
}

.form-container {
  padding: 20rpx;
}

.form-item {
  margin-bottom: 20rpx;
}

.label {
  display: block;
  font-size: 40rpx;
  color: #333333;
  margin-bottom: 20rpx;
}

.input {
  width: 100%;
  height: 60rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 5rpx;
  padding: 0 15rpx;
  font-size: 35rpx;
  box-sizing: border-box;
}

.picker-input {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 5rpx;
  padding: 0 15rpx;
  font-size: 35rpx;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
}

.button-group {
  display: flex;
  gap: 15rpx;
  margin-top: 30rpx;
}

:deep(.uni-picker-container) {
  font-size: 40rpx;
  margin-bottom: 5rpx;
}


.cancel-btn,
.confirm-btn {
  flex: 1;
  border-radius: 5rpx;
  font-size: 35rpx;
  margin-top: 10rpx;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333333;
}

.confirm-btn {
  background-color: #27ba9b;
  color: #ffffff;
}
</style>